package temp;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 逆序对
 */
public class InversePair {

    public static List<int[]> res = new ArrayList<>();

    public static void inversePair(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        process(arr, 0, arr.length - 1);
    }

    public static void process(int[] arr, int l, int r) {
        if (l == r) {
            return;
        }
        int mid = l + ((r - l) >> 1);
        process(arr, l, mid);
        process(arr, mid + 1, r);
        merge(arr, l, mid, r);
    }

    private static void merge(int[] arr, int l, int mid, int r) {
        int[] help = new int[r - l + 1];
        int p1 = l;
        int p2 = mid + 1;
        int index = 0;
        while (p1 <= mid && p2 <= r) {
            if (arr[p1] > arr[p2]) {
                for (int i = p2; i <= r; i++) {
                    res.add(new int[]{arr[p1], arr[i]});
                }
                help[index++] =arr[p1++];
            } else {
                help[index++] =arr[p2++];
            }
        }
        while (p1 <= mid) {
            help[index++] =arr[p1++];
        }
        while (p2 <= r) {
            help[index++] =arr[p2++];
        }
        for (int i = 0; i < help.length; i++) {
            arr[l + i] = help[i];
        }
    }

    public static void main(String[] args) {
        int[] arr = {1,3,5,4,0};
        inversePair(arr);
        for (int i = 0; i < res.size(); i++) {
            System.out.println(Arrays.toString(res.get(i)));
        }

    }
}
